<template>
  <div>
    <el-dialog
      class="dialog_modal"
      :title="translate('jcsj')"
      :visible.sync="isOpenSelVideo"
      width="1300px"
    >
      <div>
        <QueryForm
          v-model="filtersSel"
          :query-form-config="queryFormConfigSel"
          @handleQuery="getListSel(1)"
          @clear="clearSel"
        />
        <div class="selList">
          <div v-for="item in videoList" :key="item.id" class="item">
            <el-radio
              v-model="param.videoPath"
              :label="item.videoUrl"
              @change="radioVideoChange"
            >
              <el-image :src="item.gifName" class="spimg" />
              <div class="spbt">
                {{ item.goalType
                }}{{
                  item.goalSore
                    ? "｜" + item.goalSore + translate("fenqiu")
                    : ""
                }}
              </div>
              <div class="sptime">{{ item.goalTime }}</div>
            </el-radio>
          </div>
        </div>
        <Paginations
          :total="videoTotalCount"
          :page="paginationVideo.page"
          @current-change="getListSel"
          @SizeChange="videoPageSizeChange"
        />
      </div>
    </el-dialog>
    <el-drawer
      title="抖音发布视频"
      size="820px"
      :visible.sync="isShowModal"
      @close="closeDrawer"
    >
      <div class="mb20">
        <span class="property-title">抖音发布</span>
        <span class="sub-title">支持配置发布至抖音的账号、视频等核心信息</span>
      </div>
      <el-form
        ref="modal"
        :model="param"
        :rules="rules"
        label-suffix="："
        label-width="auto"
      >
        <el-form-item label="发布账号">
          <el-radio
            v-model="param.accountFlag"
            label="1"
            @change="getAuthList"
          >全部账号</el-radio>
          <el-radio
            v-model="param.accountFlag"
            label="0"
            @change="getAuthList('1')"
          >指定账号</el-radio>
          <el-button plain @click="handleImpower">新增授权</el-button>
        </el-form-item>
        <el-form-item v-if="param.accountFlag == '0'" prop="userId">
          <el-checkbox-group v-model="param.userId">
            <el-checkbox
              v-for="item in authAccountList"
              :key="item.id"
              :label="item.userId"
            >{{ item.dyNickName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="视频来源" prop="videoFrom">
          <el-radio v-model="param.videoFrom" label="0">上传视频</el-radio>
          <el-radio v-model="param.videoFrom" label="1">精彩视频</el-radio>
          <!-- <el-select v-model="param.videoFrom" :disabled="Boolean(param.id)">
            <el-option label="上传视频" value="0" />
            <el-option label="精彩视频" value="1" />
          </el-select> -->
        </el-form-item>
        <el-form-item label="选择视频" prop="videoPath">
          <div class="df_ac">
            <div v-if="param.videoPath && !isShowProgress" class="mr20">
              <video :src="param.videoPath" controls style="width: 186px" />
            </div>
            <el-progress
              v-if="isShowProgress"
              type="circle"
              :percentage="videoProgress"
            />
            <div v-if="param.videoFrom == '0'" class="df_ac">
              <el-upload
                v-if="!Boolean(param.id)"
                class="device-uploader2"
                :action="uploadFileUrl"
                :data="uploadParam"
                accept=".mp4,ogg,flv,avi,wmv,mov"
                :show-file-list="false"
                :before-upload="videoBefore"
                :on-progress="videoUploadPro"
                :on-success="(e) => UploadSuccess(e, 'videoPath')"
              >
                <div>
                  <i class="el-icon-plus uploader-icon" />
                  <div class="placeholder9">
                    {{ param.videoPath ? "重新上传视频" : "上传视频" }}
                  </div>
                </div>
              </el-upload>
              <div class="placeholder9">
                <div>视频大小不能超过50M，支持常用视频格式，推荐使用 mp4</div>
                <div>
                  为了更好的观看体验，推荐上传 9:16，分辨率为 720p（720x1280）{{
                    translate("andAbove")
                  }}的竖版视频。
                </div>
              </div>
            </div>
          </div>
          <el-button
            v-if="param.videoFrom == '1' && !Boolean(param.id)"
            type="primary"
            @click="handleOpenSel"
          >选择精彩瞬间视频</el-button>
        </el-form-item>
        <el-form-item label="视频封面" prop="videoCover">
          <div class="df_ac">
            <el-upload
              class="device-uploader"
              :action="uploadFileUrl"
              :data="uploadParam"
              accept=".jpg,.png"
              :show-file-list="false"
              :on-success="(e) => UploadSuccess(e, 'videoCover')"
            >
              <div>
                <i
                  v-if="!Boolean(param.id)"
                  class="el-icon-plus uploader-icon"
                />
                <div class="placeholder9">{{ translate("uploadPic") }}</div>
              </div>
              <div
                v-show="param.videoCover"
                class="file"
                :style="'background-image: url(' + param.videoCover + ')'"
              >
                <div v-if="!Boolean(param.id)" class="delete">
                  <i
                    class="el-icon-delete icon"
                    @click.stop="deleteDeviceConfigAddImage('videoCover')"
                  />
                </div>
              </div>
            </el-upload>
            <div class="placeholder9">
              <div>封面尺寸建议：720*1280px, 不大于2M。</div>
              <div>(非必传，如果不传封面图，将使用视频封面)</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="视频标题">
          <el-input
            v-model="param.videoTitle"
            class="w400"
            maxlength="50"
            show-word-limit
            placeholder="请输入抖音标题"
          />
        </el-form-item>
        <el-form-item label="热门话题">
          <el-select
            v-model="param.videoTopicTemp"
            collapse-tags
            multiple
            class="w400"
            :disabled="Boolean(param.id)"
            @change="changeTopic"
          >
            <el-option
              v-for="(item, i) in HotTopicList"
              :key="i.content"
              :label="item.content"
              :value="item.title"
            />
          </el-select>
          <el-button
            plain
            class="ml10"
            @click="getHotToppic"
          >获取热门话题</el-button>
        </el-form-item>
        <el-form-item label="视频话题">
          <el-input
            v-model="param.videoTopic"
            :disabled="Boolean(param.id)"
            class="w400"
            :autosize="{ minRows: 5, maxRows: 5 }"
            maxlength="400"
            show-word-limit
            type="textarea"
            :placeholder="translate('qsr')"
          />
          <div class="placeholder9">
            多个话题使用#分割,话题请勿包含逗号(,)，如：#话题1#话题2。可选择热门话题
          </div>
        </el-form-item>

        <div class="mb20">
          <span class="property-title">挂载设置</span>
          <span
            class="sub-title"
          >支持挂载门店地址或者抖音小程序，没有则无需填写</span>
        </div>

        <el-form-item label="挂载类型">
          <el-radio
            v-model="param.mountType"
            label="0"
            @change="changeMount"
          >POI门店地址</el-radio>
          <el-radio
            v-model="param.mountType"
            label="1"
            @change="changeMount"
          >抖音小程序</el-radio>
        </el-form-item>
        <template v-if="param.mountType == '0'">
          <el-form-item label="视频定位">
            <div class="df_ac">
              <dh-area
                :province="param.proName"
                :city="param.cityName"
                :area="param.areaName"
                :province-code="param.proCode"
                :city-code="param.cityCode"
                :area-code="param.areaCode"
                :is-show-area="false"
                @change="handleAreaChange($event)"
              />
              <el-input
                v-model="param.queryAds"
                class="w200"
                placeholder="请输入搜索地点"
              />
              <el-button
                type="primary"
                @click="queryAdsList"
              >搜索位置</el-button>
            </div>
          </el-form-item>
          <el-form-item label="门店地址">
            <el-select
              v-model="param.poiId"
              class="w400"
              placeholder="请选择视频中挂载的推广门店地址"
              :disabled="Boolean(param.id)"
            >
              <el-option
                v-for="item in shopsAddressList"
                :key="item.poiId"
                :label="item.address"
                :value="item.poiId"
              />
            </el-select>
            <div class="placeholder9">地点名称从搜索获取，无需自行添加！</div>
          </el-form-item>
        </template>
        <template v-if="param.mountType == '1'">
          <el-form-item label="小程序标题">
            <el-input
              v-model="param.dyMpTitle"
              class="w400"
              maxlength="100"
              placeholder="请输入小程序标题"
            />
          </el-form-item>
          <el-form-item label="小程序APPID">
            <el-input
              v-model="param.dyMpAppid"
              class="w400"
              maxlength="100"
              placeholder="请输入小程序小程序APPID"
            />
          </el-form-item>
          <el-form-item label="小程序PATH">
            <el-input
              v-model="param.dyMpPath"
              class="w400"
              maxlength="100"
              placeholder="请输入小程序PATH地址，如pages/index/index，选填"
            />
          </el-form-item>
        </template>
        <el-form-item>
          <el-button @click="isShowModal = false">{{
            translate("cancel")
          }}</el-button>
          <el-button type="primary" @click="onSubmit">发 布</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  uploadFile,
  DyPublishAdd,
  DyImpower,
  DyPublishAccountList,
  DyPublishHotTopic,
  DyPublishGetAdsByStr,
  DyImpowerPage,
  momVideoList,
  momSiteList,
  DyImpowerUploadVideo,
  DyImpowerUploadPhoto
} from '@/api'
import { Loading } from 'element-ui'
import DhArea from '@/components/DhArea'
export default {
  components: {
    DhArea
  },
  data() {
    return {
      param: {
        userId: [],
        videoTopicTemp: [],
        accountFlag: '1',
        videoFrom: '0'
      },
      accountList: [],
      authAccountList: [],
      HotTopicList: [],
      shopsAddressList: [],

      isShowModal: false,
      isOpenSelVideo: false,
      videoProgress: 0,
      isShowProgress: false,
      filtersSel: {},
      videoList: [],
      videoTotalCount: 0,
      paginationVideo: {
        rows: 10,
        page: 1
      },
      siteList: [],
      modalDialog: this.$store.state.app.dialog,
      rules: {
        videoFrom: [{ required: true, message: '请选择视频来源', trigger: 'change' }],
        videoPath: [{ required: true, message: '请上传视频', trigger: 'blur' }],
        userId: [{ required: true, message: '请选择发布账号', trigger: 'blur' }]
        // videoTitle: [{ required: true, message: '请输入视频文案', trigger: 'blur' }]
        // videoCover: [{ required: true, message: '请上传封面', trigger: 'blur' }]
      },
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'DY_MEDIA'
      },
      queryFormConfigSel: {
        formItems: [
          {
            filed: 'siteId',
            type: 'select',
            label: '选择场地',
            labelCode: 'siteName',
            valueCode: 'zid',
            options: []
          },
          {
            filed: 'date',
            type: 'date',
            label: '日期',
            placeholder: '请选择日期'
          },
          {
            filed: 'selTime',
            type: 'timePicker',
            label: '时间段',
            placeholder: '请选择时间段'
          }
        ],
        online: true
      }
    }
  },
  created() {
    // this.getAuthList()
  },
  methods: {
    onSubmit() {
      this.$refs['modal'].validate((valid) => {
        if (valid) {
          const { param } = this
          if (param.poiId) {
            param.address = this.shopsAddressList.find(i => i.poiId === param.poiId).address
          }
          DyPublishAdd({ param: { ...param, userId: param.userId.join(',') }}).then(res => {
            if (res.errorCode !== '000000') return
            this.$message.success('发布成功')
            this.isShowModal = false
            this.$emit('close')
            this.$emit('success')
          })
        }
      })
    },
    handleImpower() {
      DyImpowerPage({ param: {}}).then(res => {
        if (res.errorCode !== '000000') return
        window.open(res.record, '_blank')
      })
    },
    changeMount(val) {
      if (val === '1') {
        this.$set(this.param, 'poiId', '')
      } else {
        this.$set(this.param, 'dyMpTitle', '')
        this.$set(this.param, 'dyMpAppid', '')
        this.$set(this.param, 'dyMpPath', '')
      }
    },
    queryAdsList() {
      if (!this.param.queryAds) {
        return this.$message.warning('请先输入搜索地点')
      }
      DyPublishGetAdsByStr({
        param: {
          keyword: this.param.queryAds || '',
          cityName: this.param.cityName
        }
      }).then(res => {
        this.shopsAddressList = res.record.list
      })
    },
    closeDrawer() {
      this.isShowModal = false
      this.$emit('close')
    },
    handleOpenSel() {
      this.isOpenSelVideo = true
      this.getSite()
      this.getListSel()
    },
    getAuthList(val) {
      this.param.userId = []
      if (val && val === '1') {
        DyPublishAccountList({ param: {}}).then(res => {
          this.authAccountList = res.recordList || []
        })
      }
    },
    getHotToppic() {
      DyPublishHotTopic({ param: {}}).then(res => {
        if (res.errorCode !== '000000') return
        this.HotTopicList = res.recordList || []
        this.$message.success('获取成功')
      })
    },
    deleteDeviceConfigAddImage(val) {
      this.$set(this.param, val, '')
    },
    getListSel(page) {
      const { filtersSel, paginationVideo } = this
      paginationVideo.page = page || paginationVideo.page
      if (filtersSel.selTime && filtersSel.selTime.length > 0) {
        filtersSel.beginTime = filtersSel.selTime[0]
        filtersSel.endTime = filtersSel.selTime[1]
      } else {
        filtersSel.beginTime = null
        filtersSel.endTime = null
      }
      momVideoList({ param: filtersSel, pagination: paginationVideo }).then(res => {
        this.videoList = res.recordList || []
        this.videoTotalCount = res.totalCount
      }, () => {
      })
    },
    getSite() {
      momSiteList({ param: {}}).then(res => {
        this.queryFormConfigSel.formItems[0].options = res.recordList || []
      })
    },
    changeTopic(e) {
      if (e && e.length > 0) {
        this.$set(this.param, 'videoTopic', '#' + e.join('#'))
      }
    },
    videoBefore() {
      this.videoProgress = 0
      this.isShowProgress = true
    },
    videoUploadPro(e, file, files) {
      this.videoProgress = e.percent
      // console.log('videoProgress', e)
      // console.log('e', e)
      // console.log('file', file)
      // console.log('files', files)
    },
    radioVideoChange(v) {
      const loadingInstance = Loading.service({
        target: 'dialog_modal',
        text: '正在上传至抖音服务器......'
      })
      this.isShowProgress = true
      DyImpowerUploadVideo({ param: { userIds: this.param.userId.join(','), mediaPath: v }}).then(res => {
        if (res.errorCode !== '000000') return
        this.isShowProgress = false
        this.$set(this.param, 'videoPath', v)
        this.$set(this.param, 'videoData', res.record)
        this.isOpenSelVideo = false
        loadingInstance.close()
      }, () => {
        this.isShowProgress = false
        loadingInstance.close()
      })
    },
    UploadSuccess(e, str) {
      if (str === 'videoPath') {
        DyImpowerUploadVideo({ param: { userIds: this.param.userId.join(','), mediaPath: e.showUrl }}).then(res => {
          if (res.errorCode !== '000000') return
          this.isShowProgress = false
          this.$set(this.param, str, e.showUrl)
          this.$set(this.param, 'videoData', res.record)
        }, () => {
          this.isShowProgress = false
        })
      } else {
        DyImpowerUploadPhoto({ param: { userIds: this.param.userId.join(','), mediaPath: e.showUrl }}).then(res => {
          if (res.errorCode !== '000000') return
          this.$set(this.param, str, e.showUrl)
          this.$set(this.param, 'videoCoverData', res.record)
        })
      }
    },
    clearSel() {
      this.filtersSel = {}
      this.getListSel(1)
    },
    handleAreaChange(e) {
      this.$set(this.param, 'proCode', e[0].label)
      this.$set(this.param, 'proName', e[0].value)
      this.$set(this.param, 'cityCode', e[1].label)
      this.$set(this.param, 'cityName', e[1].value)
    },
    videoPageSizeChange(val) {
      this.paginationVideo.rows = val
      this.getListSel()
    },
    getAccountList() {
      DyImpower({ param: {}}).then(res => {
        this.accountList = res.recordList || []
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.selList {
  display: flex;
  flex-wrap: wrap;
  .item {
    width: 200px;
    margin: 20px;
  }
}
.device-uploader {
  width: 80px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  line-height: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.device-uploader2 {
  width: 80px;
  height: 120px;
  display: flex;
  line-height: 20px;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
</style>
